package sliver.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Repository;

import sliver.dao.TagLogDao;
import sliver.entity.Province;
import sliver.entity.Tag;
import sliver.entity.TagLog;
import sliver.utils.CalendarUtil;

@Repository
public class TagLogDaoImpl extends BaseDaoImpl<TagLog> implements TagLogDao {

	@Override
	public List<Object> obtainEachTagAvgPrice(List<Integer> tagIds, Integer position, List<Long> provinceIds, String showTimes) {
		
		List<Object> params = new ArrayList<Object>();
		
		String paramString = "";
		for(int index = 0; index < tagIds.size(); index++){
			paramString += "?,";
			params.add(tagIds.get(index));
		}
		paramString = paramString.substring(0, paramString.length() - 1);
		
		params.add(position);
		
		String provinceIdsWhere = "";
		for(int index = 0; index < provinceIds.size(); index++){
			provinceIdsWhere += "?,";
			params.add(provinceIds.get(index));
		}
		provinceIdsWhere = provinceIdsWhere.substring(0, provinceIdsWhere.length() - 1);
		
		String showTimesWhere = "";
		String[] showTimesParts = showTimes.split(" ");
		for(int index = 0; index < showTimesParts.length; index++){
			showTimesWhere += "?,";
			params.add(showTimesParts[index]);
		}
		showTimesWhere = showTimesWhere.substring(0, showTimesWhere.length() - 1);
		
		String queryString = "SELECT l.* " +
							 "FROM box_taglog l, box_tag tag , box_province province, box_rel_taglog_province rel " +
							 "WHERE l.tag_id = tag.id " +
							 "AND l.id = rel.taglog_id " +
							 "AND province.id = rel.province_id " + 
							 "AND tag.id in (" + paramString + ") " +
							 "AND l.position = ? " +
							 "AND province.id in (" + provinceIdsWhere + ") " +
							 "AND l.moment in (" + showTimesWhere + ")";
		
		queryString = "SELECT FORMAT(AVG(l.price),2) FROM (" + queryString + ") l GROUP BY l.tag_id";
		
		System.out.println(queryString);
		
		
		return complexQueryFields(queryString, params.toArray());
	}
	
	@Override
	public void logTagPrice(Tag tag, Double price, Integer position, Set<Province> provinces) {
		TagLog tagLog = new TagLog();
		
		tagLog.setMoment(CalendarUtil.getHour());
		tagLog.setPrice(price);
		tagLog.setTag(tag);
		tagLog.setPosition(position);
		tagLog.setProvinces(provinces);
		
		insert(tagLog);
	}

	@Override
	public void logTagPrice(Tag[] tags, Double price, Integer position, Set<Province> provinces) {
		for(Tag tag : tags){
			logTagPrice(tag, price, position, provinces);
		}
	}
}
